var zTreeObj;
// opts 可从网站在线制作
var opts = {
	lines : 13, // 花瓣数目
	length : 18, // 花瓣长度
	width : 10, // 花瓣宽度
	radius : 18, // 花瓣距中心半径
	corners : 1, // 花瓣圆滑度 (0-1)
	rotate : 0, // 花瓣旋转角度
	direction : 1, // 花瓣旋转方向 1: 顺时针, -1: 逆时针
	color : '#000000', // 花瓣颜色
	speed : 2, // 花瓣旋转速度
	trail : 60, // 花瓣旋转时的拖影(百分比)
	shadow : false, // 花瓣是否显示阴影
	hwaccel : false, // spinner 是否启用硬件加速及高速旋转
	className : 'spinner', // spinner css 样式名称
	zIndex : 2e9, // spinner的z轴 (默认是2000000000)
	top : "40%", // spinner 相对父容器Top定位 单位 px
	left : "52%"// spinner 相对父容器Left定位 单位 px
};

var spinner = new Spinner(opts);
var spinner1 = new Spinner(opts);

function addHoverDom(treeId, treeNode) {

	var sObj = $("#" + treeNode.tId + "_span");
	// alert("当前节点ID:"+treeNode.id);
	if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0)
		return;
	var addStr = "<span class='glyphicon glyphicon-plus-sign' id='addBtn_"
			+ treeNode.tId
			+ "' title='add node' onfocus='this.blur();'></span>";
	if ((0 == treeNode.id)) {
		addStr += "<span class='glyphicon glyphicon-folder-close' id='addFolderBtn_"
				+ treeNode.tId
				+ "' title='add folder' onfocus='this.blur();'></span>";
	}
	if ((0 != treeNode.id) && !(treeNode.isParent)) {
		addStr += "<span class='glyphicon glyphicon-edit' id='editBtn_"
				+ treeNode.tId
				+ "' title='delete node' onfocus='this.blur();'></span>";
		addStr += "<span class='glyphicon glyphicon-trash' id='removeBtn_"
				+ treeNode.tId
				+ "' title='remove node' onfocus='this.blur();'></span>";
		addStr += "<span class='glyphicon glyphicon-heart-empty' id='copyBtn_"
				+ treeNode.tId
				+ "' title='copy node' onfocus='this.blur();'></span>";// glyphicon
		// glyphicon-heart-empty

	}
	if (treeNode.isParent && (0 != treeNode.id)) {
		addStr += "<span class='glyphicon glyphicon-edit' id='editBtn_"
				+ treeNode.tId
				+ "' title='delete node' onfocus='this.blur();'></span>";
		addStr += "<span class='glyphicon glyphicon-trash' id='removeBtn_"
				+ treeNode.tId
				+ "' title='remove node' onfocus='this.blur();'></span>";
		addStr += "<span class='glyphicon glyphicon-folder-close' id='addFolderBtn_"
				+ treeNode.tId
				+ "' title='add folder' onfocus='this.blur();'></span>";
	}
	sObj.after(addStr);

	var addBtn = $("#addBtn_" + treeNode.tId);
	if (addBtn) {
		addBtn.bind("click", function() {
			var zTreeObj = $.fn.zTree.getZTreeObj("zTree");
			// alert("点击了添加按钮的方法");
			// alert("属性值ID:" + treeNode.id + ":" + treeId + ":" +
			// treeNode.tId);
			var name = "请输入新用例名称";
			var parentId = treeNode.id;
			var isParent = false;
			var caseType = "HTTP";
			var id = "";
			if (!treeNode.isParent) {
				var parentId = treeNode.getParentNode().id;
			}
			$.ajax({
				type : "POST",
				url : "addNode.action?parentId=" + parentId + "&name=" + name
						+ "&isParent=" + isParent + "&caseType=" + caseType,
				data : "",
				async : false,
				cache : false,
				success : function(msg) {
					id = msg;
					var newNode = {
						id : id,
						name : name,
						isParent : isParent
					};
					if (!treeNode.isParent) {
						newNode = zTreeObj.addNodes(treeNode.getParentNode(),
								newNode);
					} else {
						newNode = zTreeObj.addNodes(treeNode, newNode);
					}
					$.each(newNode, function(n, value) {
						zTreeObj.editName(zTreeObj.getNodeByTId(value.tId));
					});
				},
				error : function(e) {
					alert("对不起，后台处理发生异常，请联系管理员!");
				}
			});

		});
	}

	var copyBtn = $("#copyBtn_" + treeNode.tId);
	if (copyBtn) {
		copyBtn.bind("click", function() {
			var zTreeObj = $.fn.zTree.getZTreeObj("zTree");
			var name = "复制-" + treeNode.name;
			var parentId = treeNode.getParentNode().id;
			var isParent = false;
			var caseType = "HTTP";
			var fromId = treeNode.id;
			var id = "";

			$.ajax({
				type : "POST",
				url : "copyHttpNode.action?parentId=" + parentId + "&name="
						+ name + "&isParent=" + isParent + "&caseType="
						+ caseType + "&fromId=" + fromId,
				data : "",
				async : false,
				cache : false,
				success : function(msg) {
					id = msg;
					var newNode = {
						id : id,
						name : name,
						isParent : isParent
					};
					if (!treeNode.isParent) {
						newNode = zTreeObj.addNodes(treeNode.getParentNode(),
								newNode);
					} else {
						newNode = zTreeObj.addNodes(treeNode, newNode);
					}
					$.each(newNode, function(n, value) {
						zTreeObj.editName(zTreeObj.getNodeByTId(value.tId));
					});
				},
				error : function(e) {
					alert("对不起，后台处理发生异常，请联系管理员!");
				}
			});

		});
	}

	var editBtn = $("#editBtn_" + treeNode.tId);
	if (editBtn) {
		editBtn.bind("click", function() {
			// alert("点击了编辑按钮的方法");
			// alert("属性值ID:" + this.id + "-tId:" + treeNode.tId);
			var treeObj = $.fn.zTree.getZTreeObj("zTree");
			treeObj.editName(treeObj.getNodeByTId(treeNode.tId));

		});
	}
	var removeBtn = $("#removeBtn_" + treeNode.tId);
	if (removeBtn) {
		removeBtn.bind("click", function() {

			if (!confirm("确认删除?")) {
				return;
			}
			var treeObj = $.fn.zTree.getZTreeObj("zTree");
			var node = treeObj.getNodeByTId(treeNode.tId);
			var id = "";
			if (treeNode.isParent) {
				id = treeNode.id;
				id = getAllChildrenNodes(treeObj, treeNode, id);
				treeObj.removeNode(node);
			} else {
				id = treeNode.id;
				treeObj.removeNode(node);
			}
			// alert(id);
			$.ajax({
				type : "POST",
				url : "deleteNode.action?id=" + id,
				data : "",
				async : false,
				cache : false,
				success : function(msg) {
					// alert(msg);
				},
				error : function(e) {
					alert("对不起，后台处理发生异常，请联系管理员!");
				}
			});
		});
	}
	var addFolderBtn = $("#addFolderBtn_" + treeNode.tId);
	if (addFolderBtn) {
		addFolderBtn.bind("click", function() {
			// alert("点击了添加文件夹按钮的方法");
			// alert("属性值ID:" + this.id);
			var zTreeObj = $.fn.zTree.getZTreeObj("zTree");
			var name = "请输入新文件夹名称";
			var parentId = treeNode.id;
			var isParent = true;
			var caseType = "HTTP";
			var id = "";
			// if (!treeNode.isParent) {
			// var parentId = treeNode.getParentNode().id;
			// }
			$.ajax({
				type : "POST",
				url : "addNode.action?parentId=" + parentId + "&name=" + name
						+ "&isParent=" + isParent + "&caseType=" + caseType,
				data : "",
				async : false,
				cache : false,
				success : function(msg) {
					id = msg;
				},
				error : function(e) {
					alert("对不起，后台处理发生异常，请联系管理员!");
				}
			});

			var newNode = {
				id : id,
				name : name,
				isParent : isParent
			};
			if (!treeNode.isParent) {
				newNode = zTreeObj.addNodes(treeNode.getParentNode(), newNode);
			} else {
				newNode = zTreeObj.addNodes(treeNode, newNode);
			}
			// alert("新节点信息:" + JSON.stringify(newNode));
			$.each(newNode, function(n, value) {
				// alert(n + ":" + value.tId);
				zTreeObj.editName(zTreeObj.getNodeByTId(value.tId));
			});
		});
	}
};
function removeHoverDom(treeId, treeNode) {
	$("#addBtn_" + treeNode.tId).unbind().remove();
	$("#removeBtn_" + treeNode.tId).unbind().remove();
	$("#editBtn_" + treeNode.tId).unbind().remove();
	$("#addFolderBtn_" + treeNode.tId).unbind().remove();
	$("#copyBtn_" + treeNode.tId).unbind().remove();
};
function zTreeOnRename(event, treeId, treeNode, isCancel) {
	// alert(treeNode.tId + ", " + treeNode.name);
	// alert(treeNode);
	// isCancel=true;
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	if (treeNode.name.length < 1) {
		treeObj.cancelEditName();
		// alert("名称不允许为空!");
		return;
	}
	$.ajax({
		type : "POST",
		url : "updateNode.action?id=" + treeNode.id + "&name=" + treeNode.name,
		data : "",
		async : false,
		cache : false,
		success : function(msg) {
			// alert(msg);
			treeObj.setting.callback.onClick(null, treeId, treeNode);// 调用事件
		},
		error : function(e) {
			alert("对不起，后台处理发生异常，请联系管理员!");
		}
	});
}
// function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
// var treeObj = $.fn.zTree.getZTreeObj("zTree");
// var node = treeObj.getNodeByTId("zTree_1");
// alert(node);
// treeObj.hideNode(node);
// }

function navigation(treeNode, str) {
	if (treeNode.id == 0) {
		str = "<li class=\"active\">" + treeNode.name + "</li>" + str;
		str = "<li><em class=\"glyphicon glyphicon-home\"></em></li>" + str;
		return str;
	} else {
		// alert(treeNode.isParent);
		if (treeNode.isParent) {
			str = "<li class=\"active\">" + treeNode.name + "</li>" + str;
		} else {
			str = "<li class=\"active\">" + treeNode.name + "(interface-"
					+ treeNode.id + ")" + "</li>" + str;
		}
		return navigation(treeNode.getParentNode(), str);
	}
}

function onClick(event, treeId, treeNode, clickFlag) {
	if (treeNode.isParent) {
		return;
	}
	$
			.ajax({
				url : "getCaseJson.action",
				type : "POST",
				data : "caseId=" + treeNode.id,
				dataType : "json",
				// async : false,
				// cache : false,
				beforeSend : function() {
					var target = $("#firstDiv").get(0);
					spinner.spin(target);
				},
				success : function(json) {

					spinner.spin();

					$("#pageNavigation").empty();

					var result = "";
					result = navigation(treeNode, result);
					$("#pageNavigation").prepend(result);
					var httpCase = jQuery.parseJSON(json.httpCaseJson);
					$("#inputURL").val("");
					if (httpCase != null) {
						$("#inputURL").val(httpCase.httpUrl);
						$("#methodControl").val(httpCase.httpMethod);
						var p1 = $("#methodControl")
								.children('option:selected').val();
						if ("POST" == p1) {
							$("#bodyContol").show();
						} else if ("GET" == p1) {
							$("#bodyContol").hide();
						}
					} else {
						$("#methodControl").val("GET");
						var p1 = $("#methodControl")
								.children('option:selected').val();
						if ("POST" == p1) {
							$("#bodyContol").show();
						} else if ("GET" == p1) {
							$("#bodyContol").hide();
						}
					}

					var runBeforel = jQuery.parseJSON(json.runBeforesJson);
					$("#runBeforeAll").empty();
					$
							.each(
									runBeforel,
									function(i, runBefore) {
										var htmlA = "<div class=\"input-append\"><div class=\"col-sm-3\"><select class=\"form-control\" id=\"beforeClass\" name=\"runBefore\"><option>"
												+ runBefore.classPath
												+ "</option></select></div><div class=\"col-sm-3\"><select class=\"form-control\" id=\"beforeMethod\" name=\"runBefore\"><option>"
												+ runBefore.beforeMethod
												+ "</option></select></div><div class=\"col-sm-5\"><input class=\"form-control\" id=\"beforeArgs\"	value=\""
												+ runBefore.beforeMethodArgs
												+ "\" name=\"runBefore\" placeholder=\"根据方法输入参数，以逗号隔开\" /></div><div><a class=\"glyphicon glyphicon-remove\" href=\"javascript:void(0)\" id=\"runBeforeDel\" style=\"line-height: 35px\"></a></div></div>";
										$("#runBeforeAll").prepend(htmlA);
									});

					var headerl = jQuery.parseJSON(json.headersJson);
					$("#headerAll").empty();
					var htmlA = "<div class=\"input-append\"><div class=\"col-sm-4\"><input class=\"form-control\" id=\"headerAttr\" name=\"headers\" placeholder=\"Hearder attribute key\" /></div><div class=\"col-sm-4\"><input class=\"form-control\" id=\"headerAttr\" name=\"headers\" placeholder=\"Value\" /></div><div class=\"col-sm-2\"><button class=\"glyphicon glyphicon-plus btn btn-primary\" id=\"headerAdd\" type=\"button\"></botton></div></div>";
					$("#headerAll").prepend(htmlA);
					$
							.each(
									headerl,
									function(i, header) {
										if (i == 0) {
											$('input[name="headers"]')
													.each(
															function(j) {
																if (j == 0)
																	$(this)
																			.val(
																					header.key);
																if (j == 1)
																	$(this)
																			.val(
																					header.value);
															});
										} else {
											var htmlA = "<div class=\"input-append\"><div class=\"col-sm-4\"><input class=\"form-control\" id=\"headerAttr\" value=\""
													+ header.key
													+ "\" name=\"headers\" placeholder=\"Hearder attribute key\" /></div><div class=\"col-sm-4\"><input class=\"form-control\" id=\"headerAttr\" value=\""
													+ header.value
													+ "\" name=\"headers\" placeholder=\"Value\" /></div><div><a class=\"glyphicon glyphicon-remove\" id=\"headerRemove\" href=\"javascript:void(0)\" style=\"line-height:35px\"></a></div></div>";
											$("#headerAll").prepend(htmlA);
										}
									});
					var urlParaml = jQuery.parseJSON(json.urlParamsJson);
					$("#URLAll").empty();
					var htmlA = "<div class=\"input-append\"><div class=\"col-sm-4\"><input class=\"form-control\" id=\"URLAttr\" name=\"urlParams\" placeholder=\"URL parameter key\" /></div><div class=\"col-sm-4\"><input class=\"form-control\" id=\"URLAttr\" name=\"urlParams\" placeholder=\"Value\" /></div><div class=\"col-sm-2\"><button class=\"glyphicon glyphicon-plus btn btn-primary\" id=\"URLAdd\" type=\"button\"></botton></div></div>";
					$("#URLAll").prepend(htmlA);
					$
							.each(
									urlParaml,
									function(i, urlParam) {
										if (i == 0) {
											$('input[name="urlParams"]')
													.each(
															function(j) {
																if (j == 0)
																	$(this)
																			.val(
																					urlParam.key);
																if (j == 1)
																	$(this)
																			.val(
																					urlParam.value);
															});
										} else {
											var htmlA = "<div class=\"input-append\"><div class=\"col-sm-4\"><input class=\"form-control\" id=\"URLAttr\" value=\""
													+ urlParam.key
													+ "\" name=\"urlParams\" placeholder=\"URL parameter key\" /></div><div class=\"col-sm-4\"><input class=\"form-control\" id=\"URLAttr\" value=\""
													+ urlParam.value
													+ "\" name=\"urlParams\" placeholder=\"Value\" /></div><div><a class=\"glyphicon glyphicon-remove\" id=\"URLRemove\" href=\"javascript:void(0)\" style=\"line-height:35px\"></a></div></div>";
											$("#URLAll").prepend(htmlA);
										}
									});
					var entities = jQuery.parseJSON(json.entitiesJson);
					$("#rawContent").val("");
					if (entities != null) {

						if (entities.type == "x-www-form-urlencoded") {
							$("#xfuButton").removeClass("btn-default")
									.addClass("active");
							$("#rawButton").removeClass("active").addClass(
									"btn-default");
							$("#entitis_value").val("x-www-form-urlencoded");
							$("#rawContent").attr("name", "");
							$("#rawAll").hide();
							$("#rawSelect").hide();
							$("#xfuAll").show();
						} else {
							$("#rawButton").removeClass("btn-default")
									.addClass("active");
							$("#xfuButton").removeClass("active").addClass(
									"btn-default");
							$("#entitis_value").val("raw");
							$("#rawContent").attr("name", "entities.data");
							$("#xfuAll").hide();
							$("#rawAll").show();
							$("#rawSelect").show();
							$("#rawContent").val(entities.data);
						}
					}
					var nameValuePairl = jQuery
							.parseJSON(json.nameValuePairsJson);
					$("#xfuAll").empty();
					var htmlA = "<div class=\"input-append\"><div class=\"col-sm-4\"><input class=\"form-control\" id=\"xfuAttr\" name=\"nameValuePairs\" placeholder=\"Key\" /></div><div class=\"col-sm-4\"><input class=\"form-control\" id=\"xfuAttr\" name=\"nameValuePairs\" placeholder=\"Value\" /></div><div class=\"col-sm-2\"><button class=\"glyphicon glyphicon-plus btn btn-primary\" id=\"nameValuePairAdd\" type=\"button\"></botton></div></div>";
					$("#xfuAll").prepend(htmlA);
					$
							.each(
									nameValuePairl,
									function(i, nameValuePair) {
										if (i == 0) {
											$('input[name="nameValuePairs"]')
													.each(
															function(j) {
																if (j == 0)
																	$(this)
																			.val(
																					nameValuePair.key);
																if (j == 1)
																	$(this)
																			.val(
																					nameValuePair.value);
															});
										} else {
											var htmlA = "<div class=\"input-append\"><div class=\"col-sm-4\"><input class=\"form-control\" id=\"xfuAttr\" value=\""
													+ nameValuePair.key
													+ "\" name=\"nameValuePairs\" placeholder=\"Key\" /></div><div class=\"col-sm-4\"><input class=\"form-control\" id=\"xfuAttr\" value=\""
													+ nameValuePair.value
													+ "\" name=\"nameValuePairs\" placeholder=\"Value\" /></div><div><a class=\"glyphicon glyphicon-remove\" id=\"xfuRemove\" href=\"javascript:void(0)\" style=\"line-height:35px\"></a></div></div>";
											$("#xfuAll").prepend(htmlA);
										}
									});

					var runAfterl = jQuery.parseJSON(json.runAftersJson);
					$("#runAfterAll").empty();
					$
							.each(
									runAfterl,
									function(i, runAfter) {
										// alert(i);
										// $("#runAfterAll").empty();
										var htmlA = "<div class=\"input-append\"><div class=\"col-sm-3\"><select class=\"form-control\" id=\"afterClass\" name=\"runAfter\"><option>"
												+ runAfter.classPath
												+ "</option></select></div><div class=\"col-sm-3\"><select class=\"form-control\" id=\"afterMethod\" name=\"runAfter\"><option>"
												+ runAfter.afterMethod
												+ "</option></select></div><div class=\"col-sm-5\"><input class=\"form-control\" id=\"afterArgs\"	value=\""
												+ runAfter.afterMethodArgs
												+ "\" name=\"runAfter\" placeholder=\"根据方法输入参数，以逗号隔开\" /></div><div><a class=\"glyphicon glyphicon-remove\" href=\"javascript:void(0)\" id=\"runAfterDel\" style=\"line-height: 35px\"></a></div></div>";
										$("#runAfterAll").prepend(htmlA);
									});
					$("#responseSteps").val("");
					$("#responseText").val("");

				},
				error : function() {
					spinner.spin();
					alert("获取数据出现错误,请联系管理员!");
				}
			});
}

function getAllChildrenNodes(treeObj, treeNode, result) {
	if (treeNode.isParent) {
		var childrenNodes = treeNode.children;
		if (childrenNodes) {
			for (var i = 0; i < childrenNodes.length; i++) {
				if (childrenNodes[i].isParent) {
					result += ',' + childrenNodes[i].id;
					result = getAllChildrenNodes(treeObj, childrenNodes[i],
							result);
				} else {
					result += ',' + childrenNodes[i].id;
				}
			}
		}
	}
	return result;
}
var setting = {
	check : {
		enable : false
	},
	view : {
		addHoverDom : addHoverDom,
		removeHoverDom : removeHoverDom,
		dblClickExpand : true,
		showLine : true,
		selectedMulti : false
	// expandSpeed: "fast",
	// fontCss: getFontCss
	},
	data : {
		simpleData : {
			enable : true
		// idKey: "id",
		// pIdKey: "pId",
		// rootPId: 0
		},
		keep : {
			leaf : false,
			parent : true
		}
	},
	callback : {
		onRename : zTreeOnRename,
		onClick : onClick,
	// asyncSuccess: zTreeOnAsyncSuccess
	},
	edit : {
		editNameSelectAll : true
	}
};

$(document)
		.ready(
				function() {
					$.ajax({
						url : "getHttpTreeNode.action",
						type : "get",
						dataType : "json",
						success : initZtree
					});

					$("#isave").click(function() {
						var data = $("#interfaceForm").serialize();
						// data2=$("#beforeClass,#beforeMethod,#afterClass,#afterMethod").serialize();
						// alert(data2);
						// alert(data);
						var zTree = $.fn.zTree.getZTreeObj("zTree");
						var nodes = zTree.getSelectedNodes();
						// alert(nodes[0].name+",ID是："+nodes[0].id);//返回被选中节点对象
						data = data + "&caseId=" + nodes[0].id;
						$.ajax({
							type : "POST",
							url : "httpCaseSave.action",
							data : data,
							// async : false,
							// cache : false,
							beforeSend : function() {
								var target = $("#firstDiv").get(0);
								spinner1.spin(target);
							},
							success : function(msg) {

								spinner1.spin();
								// alert(msg);
							},
							error : function(e) {
								spinner1.spin();
								alert("对不起，后台处理发生异常，请联系管理员!");
							}
						});
					});

					$("#isend")
							.click(
									function() {
										var data = $("#interfaceForm")
												.serialize();
										var zTree = $.fn.zTree
												.getZTreeObj("zTree");
										var nodes = zTree.getSelectedNodes();
										data = data + "&caseId=" + nodes[0].id;
										$
												.ajax({
													type : "POST",
													url : "httpCaseSend.action",
													data : data,
													// async : false,
													// cache : false,
													beforeSend : function() {
														var target = $(
																"#firstDiv")
																.get(0);
														spinner1.spin(target);
													},
													success : function(msg) {
														spinner1.spin();
														// alert(msg);
														$("#responseSteps")
																.val(
																		msg
																				.split("$#$#$#")[0]);
														if (msg.split("$#$#$#")[1]
																.match("^\{(.+:.+,*){1,}\}$")) {
															$("#responseText")
																	.val(
																			JSON
																					.stringify(
																							jQuery
																									.parseJSON(msg
																											.split("$#$#$#")[1]),
																							null,
																							1));
														} else {
															$("#responseText")
																	.val(
																			msg
																					.split("$#$#$#")[1]);
														}
													},
													error : function(e) {
														spinner1.spin();
														alert("对不起，后台处理发生异常，请联系管理员!");
													}
												});
									});

				});

function initZtree(json) {
	var data = (json.caseNodeJson);
	var zNodes = eval("(" + data + ")");
	zTreeObj = $.fn.zTree.init($('#zTree'), setting, zNodes);

	// var treeObj = $.fn.zTree.getZTreeObj("zTree");
	// var nodes = treeObj.getNodes();
	// treeObj.hideNode(nodes[0]);
	// var node = zTreeObj.getNodeByParam("id",1,0);
	// alert(node.name);
	// treeObj.hideNode(node);

}

function submitCheckedNodes(treeNode) {
	var nodes = new Array();
	// 取得选中的结点
	nodes = zTreeObj.getCheckedNodes(true);
	var str = "";
	for (i = 0; i < nodes.length; i++) {
		if (str != "") {
			str += ",";
		}
		str += nodes[i].id;
	}
	alert(str);
}